from django.http import HttpResponse
from seeker.utils import parse_display_field
import StringIO

def format_csv( parts ):
	values = []
	for p in parts:
		val = p.replace( '"', '""' )
		if val.find(',') >= 0:
			val = '"' + val + '"'
		values.append( val )
	return ",".join( values ) + '\n'

def render( request, plugin, search, result, page=0, page_size=-1 ):
	fields = [ parse_display_field(f) for f in search.display_fields ]
	print fields
	headers = [ plugin.get_field_name(request,x[0]) for x in fields ]
	num_rows = result.count()
	print num_rows
	data = StringIO.StringIO()
	data.write( format_csv(headers) )
	for k in range(num_rows):
		row = [ result.get_value(k,x[0],x[1]) for x in fields ]
		data.write( format_csv(row) )
	response = HttpResponse( data.getvalue(), mimetype='text/csv' )
	response['Content-disposition'] = 'attachment; filename="export.csv"'
	data.close()
	return response
